package etc.server.etc;

import com.dmz.test.etc.domain.MsgClazz;
import com.dmz.test.etc.service.ServerService;
import com.dmz.test.etc.utils.SpringUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;


/**
 * @author lee
 */
@Slf4j
public class EtcServerHandler extends ChannelInboundHandlerAdapter {

    private final String encoding = "";

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("client connected: {}", ctx.channel().remoteAddress());
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("client==D==receive==start====================================================");
        // 在这里处理从客户端接收到的消息
        byte[] req = (byte[]) msg;
        if (req != null && req.length > 0) {
            log.info("D--server--receive--req:{}", req);
            ServerService bean = SpringUtil.getBean(ServerService.class);
            MsgClazz forward = bean.forward(req, ctx.channel());
            ctx.writeAndFlush(forward.getData());
        } else {
            log.error("request is null");
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("D disconnected", cause);
        ctx.close();
    }
}